package controllers

import (
	"fmt"
	"math"
	"strconv"
	"strings"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
)

type MiniStoreController struct {
	web.Controller
}

// GetStoreVenues 获取门店场地列表
func (c *MiniStoreController) GetStoreVenues() {
	// 获取门店ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := utils.ParseInt64(idStr)
	if err != nil {
		c.Data["json"] = utils.ResponseFail("无效的门店ID")
		c.ServeJSON()
		return
	}

	// 获取场地类型
	typeId, _ := c.GetInt("type_id", 0)

	// 获取场地列表
	venues, err := models.GetStoreVenuesByType(id, typeId)
	if err != nil {
		c.Data["json"] = utils.ResponseFail("获取场地列表失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")

	// 构建小程序所需的场地数据
	venueList := make([]map[string]interface{}, 0)
	for _, venue := range venues {
		// 处理场地图片
		var imageUrls []string
		if venue.Images != "" {
			utils.UnmarshalJSON(venue.Images, &imageUrls)
			for j, url := range imageUrls {
				if len(url) > 0 && url[0] == '/' {
					imageUrls[j] = baseURL + strings.ReplaceAll(url, "\\", "/")
				}
			}
		}

		// 处理场地设施
		var facilities []string
		if venue.Facilities != "" {
			utils.UnmarshalJSON(venue.Facilities, &facilities)
		}

		// 处理营业时间
		var openingHours string
		if venue.OpeningHours != "" {
			openingHours = venue.OpeningHours
		} else {
			openingHours = "24小时营业" // 默认营业时间
		}

		//获取场地套餐信息
		packages, err := models.GetVenuePackagesByVenueId(venue.Id)
		if err != nil {
			// 只记录错误，不影响正常流程
			// 忽略错误，继续处理
		}

		// 处理套餐信息
		var packageList []map[string]interface{}
		for _, pack := range packages {
			packageData := map[string]interface{}{
				"id":          pack.Id,
				"name":        pack.Name,
				"description": pack.Description,
				"price":       pack.Price,
				"duration":    pack.Duration,
			}
			packageList = append(packageList, packageData)
		}

		// 获取场地状态显示信息
		statusText := "空闲中"
		statusColor := "#4CAF50" // 默认绿色

		now := time.Now().Unix()
		order, _ := models.GetFirstUpcomingOrActiveOrder(venue.Id, now)

		if order != nil {
			if now >= order.StartTime {
				// 正在进行中
				statusText = time.Unix(order.EndTime, 0).Format("15:04") + " 结束"
				statusColor = "#FF9800" // 橙色
			} else {
				// 即将开始
				statusText = time.Unix(order.StartTime, 0).Format("15:04") + " 开始"
				statusColor = "#2196F3" // 蓝色
			}
		} else {
			// 如果没有订单，则根据场地的通用状态显示
			switch venue.Status {
			case 1:
				statusText = "空闲中"
				statusColor = "#4CAF50" // 绿色
			case 2:
				statusText = "使用中"
				statusColor = "#FF9800" // 橙色
			case 3:
				statusText = "保洁中"
				statusColor = "#2196F3" // 蓝色
			case 4:
				statusText = "待保洁"
				statusColor = "#FFC107" // 黄色
			case 5:
				statusText = "维护中"
				statusColor = "#F44336" // 红色
			case 6:
				statusText = "装修中"
				statusColor = "#9C27B0" // 紫色
			}
		}

		// 构建返回数据
		venueData := map[string]interface{}{
			"id":             venue.Id,
			"name":           venue.Name,
			"description":    venue.Description,
			"images":         imageUrls,
			"hour_price":     venue.HourPrice, // 使用正确的价格字段
			"day_price":      venue.DayPrice,  // 使用正确的价格字段
			"facilities":     facilities,
			"venue_type":     venue.VenueType, // 场地类型名称
			"store_id":       venue.StoreId,
			"status":         venue.Status,
			"status_text":    statusText,  // 状态文字描述
			"status_color":   statusColor, // 状态颜色
			"opening_hours":  openingHours,
			"special_notice": venue.SpecialNotice,
			"capacity":       venue.Capacity,
			"area":           venue.Area,
			"packages":       packageList,
		}

		venueList = append(venueList, venueData)
	}

	c.Data["json"] = utils.ResponseSuccess("获取场地列表成功", venueList)
	c.ServeJSON()
}

// GetNearbyStores 获取附近门店
func (c *MiniStoreController) GetNearbyStores() {
	miniprogramConfig := middleware.GetCurrentMiniprogramConfig(c.Ctx)
	if miniprogramConfig == nil {
		c.Data["json"] = utils.ResponseFail("未获取到小程序配置")
		c.ServeJSON()
		return
	}
	// 获取查询参数
	page, _ := c.GetInt("page", 1)
	limit, _ := c.GetInt("limit", 10)
	typeID, _ := c.GetInt("type_id", 0)
	latitude, _ := c.GetFloat("latitude", 0)
	longitude, _ := c.GetFloat("longitude", 0)
	cityName := c.GetString("city", "")

	// 构建过滤条件
	filters := make(map[string]interface{})
	filters["status"] = 1 // 只返回正常营业的门店
	if miniprogramConfig != nil {
		filters["franchise_id"] = miniprogramConfig.FranchiseId
	}
	// 如果指定了类型，添加类型过滤
	if typeID > 0 {
		filters["venue_type_id"] = typeID
	}

	// 如果指定了城市，添加城市过滤
	if cityName != "" {
		// 先查询城市ID
		city, err := models.GetCityByName(cityName)
		if err == nil && city != nil {
			filters["city_id"] = city.Id
		}
	}

	// 调用模型获取门店列表
	stores, total, err := models.GetStoreList(page, limit, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取门店列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取所有门店的最新订单时间
	storeBookingTimes := make(map[int64]string)
	storeIDs := make([]int64, 0, len(stores))
	for _, store := range stores {
		storeIDs = append(storeIDs, store.Id)
	}

	if len(storeIDs) > 0 {
		o := orm.NewOrm()
		var latestOrders []orm.Params

		// 查询每个门店最近一条预订订单的时间
		storeIDsStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(storeIDs)), ","), "[]")
		_, err := o.Raw(`
			SELECT store_id, MAX(created_at) as latest_booking
			FROM ss_order
			WHERE store_id IN (` + storeIDsStr + `) AND status IN (1,2) AND is_deleted = 0
			GROUP BY store_id
		`).Values(&latestOrders)

		if err == nil {
			now := time.Now().Unix()
			for _, order := range latestOrders {
				storeID, _ := strconv.ParseInt(order["store_id"].(string), 10, 64)
				bookingTime, _ := strconv.ParseInt(order["latest_booking"].(string), 10, 64)

				// 计算时间差（以小时为单位）
				hoursDiff := (now - bookingTime) / 3600
				var timeText string

				if hoursDiff < 1 {
					// 不到1小时，显示"刚刚"
					timeText = "刚刚"
				} else if hoursDiff < 24 {
					// 不到24小时，显示"X小时前"
					timeText = fmt.Sprintf("%d小时前", hoursDiff)
				} else {
					// 超过24小时，显示"X天前"
					daysDiff := hoursDiff / 24
					timeText = fmt.Sprintf("%d天前", daysDiff)
				}

				storeBookingTimes[storeID] = timeText
			}
		}
	}

	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")
	// 如果有位置信息，计算距离并排序
	var storeWithDistance []map[string]interface{}
	if latitude > 0 && longitude > 0 {
		// 为每个门店计算距离
		for _, store := range stores {
			distance := calculateDistance(latitude, longitude, store.Latitude, store.Longitude)
			distanceText := formatDistance(distance)

			// 解析场地类型
			venueTypes := []int{}
			if store.VenueTypes != "" {
				utils.UnmarshalJSON(store.VenueTypes, &venueTypes)
			}
			// 处理图片URL，如果不是以http开头，则添加基础URL
			imageUrl := store.Images
			if len(imageUrl) > 0 && imageUrl[0] == '/' {
				imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
			}

			// 获取该门店的最新预订时间
			bookingTime, ok := storeBookingTimes[store.Id]
			if !ok {
				// 如果没有预订记录，使用一个默认值
				bookingTime = "今日"
			}

			// 构建返回数据
			storeData := map[string]interface{}{
				"id":             store.Id,
				"name":           store.Name,
				"address":        store.Address,
				"distance":       distanceText,
				"distance_value": distance,
				"type_id":        venueTypes,
				"rating":         "5.0", // 暂时固定值，后续可接入评分系统
				"logo":           store.Logo,
				"images":         imageUrl,
				"is_hot":         store.IsHot,
				"bookingTime":    bookingTime, // 添加最新预订时间
				"businessHours":  store.BusinessHours,
			}

			storeWithDistance = append(storeWithDistance, storeData)
		}

		// 按距离排序
		utils.SortByField(storeWithDistance, "distance_value", true)
	} else {
		// 没有位置信息，直接构建返回数据
		for _, store := range stores {
			// 解析场地类型
			venueTypes := []int{}
			if store.VenueTypes != "" {
				utils.UnmarshalJSON(store.VenueTypes, &venueTypes)
			}
			// 处理图片URL，如果不是以http开头，则添加基础URL
			imageUrl := store.Images
			if len(imageUrl) > 0 && imageUrl[0] == '/' {
				imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
			}

			// 获取该门店的最新预订时间
			bookingTime, ok := storeBookingTimes[store.Id]
			if !ok {
				// 如果没有预订记录，使用一个默认值
				bookingTime = "今日"
			}

			storeData := map[string]interface{}{
				"id":            store.Id,
				"name":          store.Name,
				"address":       store.Address,
				"type_id":       venueTypes,
				"rating":        "5.0", // 暂时固定值，后续可接入评分系统
				"logo":          store.Logo,
				"images":        imageUrl,
				"is_hot":        store.IsHot,
				"bookingTime":   bookingTime, // 添加最新预订时间
				"businessHours": store.BusinessHours,
			}

			storeWithDistance = append(storeWithDistance, storeData)
		}
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取附近门店成功",
		"data": map[string]interface{}{
			"list":  storeWithDistance,
			"total": total,
			"page":  page,
			"limit": limit,
		},
	}
	c.ServeJSON()
}

// GetHotStores 获取热门门店
func (c *MiniStoreController) GetHotStores() {
	// 获取查询参数
	limit, _ := c.GetInt("limit", 5)

	// 构建过滤条件
	filters := make(map[string]interface{})
	filters["status"] = 1 // 只返回正常营业的门店
	filters["is_hot"] = 1 // 只返回热门门店

	// 调用模型获取门店列表
	stores, _, err := models.GetStoreList(1, limit, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取热门门店失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取所有门店的最新订单时间
	storeBookingTimes := make(map[int64]string)
	storeIDs := make([]int64, 0, len(stores))
	for _, store := range stores {
		storeIDs = append(storeIDs, store.Id)
	}

	if len(storeIDs) > 0 {
		o := orm.NewOrm()
		var latestOrders []orm.Params

		// 查询每个门店最近一条预订订单的时间
		storeIDsStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(storeIDs)), ","), "[]")
		_, err := o.Raw(`
			SELECT store_id, MAX(created_at) as latest_booking
			FROM ss_order
			WHERE store_id IN (` + storeIDsStr + `) AND status IN (1,2) AND is_deleted = 0
			GROUP BY store_id
		`).Values(&latestOrders)

		if err == nil {
			now := time.Now().Unix()
			for _, order := range latestOrders {
				storeID, _ := strconv.ParseInt(order["store_id"].(string), 10, 64)
				bookingTime, _ := strconv.ParseInt(order["latest_booking"].(string), 10, 64)

				// 计算时间差（以小时为单位）
				hoursDiff := (now - bookingTime) / 3600
				var timeText string

				if hoursDiff < 1 {
					// 不到1小时，显示"刚刚"
					timeText = "刚刚"
				} else if hoursDiff < 24 {
					// 不到24小时，显示"X小时前"
					timeText = fmt.Sprintf("%d小时前", hoursDiff)
				} else {
					// 超过24小时，显示"X天前"
					daysDiff := hoursDiff / 24
					timeText = fmt.Sprintf("%d天前", daysDiff)
				}

				storeBookingTimes[storeID] = timeText
			}
		}
	}

	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")
	// 构建返回数据
	var hotStores []map[string]interface{}
	for _, store := range stores {
		// 解析场地类型
		venueTypes := []int{}
		if store.VenueTypes != "" {
			utils.UnmarshalJSON(store.VenueTypes, &venueTypes)
		}
		// 处理图片URL，如果不是以http开头，则添加基础URL
		imageUrl := store.Images
		if len(imageUrl) > 0 && imageUrl[0] == '/' {
			imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
		}

		// 获取该门店的最新预订时间
		bookingTime, ok := storeBookingTimes[store.Id]
		if !ok {
			// 如果没有预订记录，使用一个默认值
			bookingTime = "今日"
		}

		storeData := map[string]interface{}{
			"id":            store.Id,
			"name":          store.Name,
			"address":       store.Address,
			"type_id":       venueTypes,
			"rating":        "5.0", // 暂时固定值，后续可接入评分系统
			"logo":          store.Logo,
			"images":        store.Images,
			"bookingTime":   bookingTime, // 添加最新预订时间
			"businessHours": store.BusinessHours,
		}

		hotStores = append(hotStores, storeData)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取热门门店成功",
		"data": map[string]interface{}{
			"list": hotStores,
		},
	}
	c.ServeJSON()
}

// SearchStores 搜索门店
func (c *MiniStoreController) SearchStores() {
	// 获取查询参数
	page, _ := c.GetInt("page", 1)
	limit, _ := c.GetInt("limit", 10)
	keyword := c.GetString("keyword")

	if keyword == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "搜索关键词不能为空",
		}
		c.ServeJSON()
		return
	}

	// 构建过滤条件
	filters := make(map[string]interface{})
	filters["status"] = 1     // 只返回正常营业的门店
	filters["name"] = keyword // 按名称搜索

	// 调用模型获取门店列表
	stores, total, err := models.GetStoreList(page, limit, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "搜索门店失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取所有门店的最新订单时间
	storeBookingTimes := make(map[int64]string)
	storeIDs := make([]int64, 0, len(stores))
	for _, store := range stores {
		storeIDs = append(storeIDs, store.Id)
	}

	if len(storeIDs) > 0 {
		o := orm.NewOrm()
		var latestOrders []orm.Params

		// 查询每个门店最近一条预订订单的时间
		storeIDsStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(storeIDs)), ","), "[]")
		_, err := o.Raw(`
			SELECT store_id, MAX(created_at) as latest_booking
			FROM ss_order
			WHERE store_id IN (` + storeIDsStr + `) AND status IN (1,2) AND is_deleted = 0
			GROUP BY store_id
		`).Values(&latestOrders)

		if err == nil {
			now := time.Now().Unix()
			for _, order := range latestOrders {
				storeID, _ := strconv.ParseInt(order["store_id"].(string), 10, 64)
				bookingTime, _ := strconv.ParseInt(order["latest_booking"].(string), 10, 64)

				// 计算时间差（以小时为单位）
				hoursDiff := (now - bookingTime) / 3600
				var timeText string

				if hoursDiff < 1 {
					// 不到1小时，显示"刚刚"
					timeText = "刚刚"
				} else if hoursDiff < 24 {
					// 不到24小时，显示"X小时前"
					timeText = fmt.Sprintf("%d小时前", hoursDiff)
				} else {
					// 超过24小时，显示"X天前"
					daysDiff := hoursDiff / 24
					timeText = fmt.Sprintf("%d天前", daysDiff)
				}

				storeBookingTimes[storeID] = timeText
			}
		}
	}

	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")

	// 构建返回数据
	var searchResults []map[string]interface{}
	for _, store := range stores {
		// 解析场地类型
		venueTypes := []int{}
		if store.VenueTypes != "" {
			utils.UnmarshalJSON(store.VenueTypes, &venueTypes)
		}

		// 处理图片URL
		imageUrl := store.Images
		if len(imageUrl) > 0 && imageUrl[0] == '/' {
			imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
		}

		// 获取该门店的最新预订时间
		bookingTime, ok := storeBookingTimes[store.Id]
		if !ok {
			// 如果没有预订记录，使用一个默认值
			bookingTime = "今日"
		}

		storeData := map[string]interface{}{
			"id":          store.Id,
			"name":        store.Name,
			"address":     store.Address,
			"type_id":     venueTypes,
			"rating":      "5.0", // 暂时固定值
			"logo":        store.Logo,
			"images":      imageUrl,
			"is_hot":      store.IsHot,
			"phone":       store.Phone,
			"distance":    "未知",        // 无位置信息时的默认值
			"bookingTime": bookingTime, // 添加最新预订时间
		}

		searchResults = append(searchResults, storeData)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "搜索门店成功",
		"data": map[string]interface{}{
			"list":  searchResults,
			"total": total,
			"page":  page,
			"limit": limit,
		},
	}
	c.ServeJSON()
}

// GetStoreDetail 获取门店详情
func (c *MiniStoreController) GetStoreDetail() {
	// 获取门店ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取门店详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 解析场地类型
	venueTypes := []int{}
	if store.VenueTypes != "" {
		utils.UnmarshalJSON(store.VenueTypes, &venueTypes)
	}

	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")

	// 处理图片URL
	imageUrl := store.Images
	if len(imageUrl) > 0 && imageUrl[0] == '/' {
		imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
	}

	// 处理Banner图片URL
	var bannerUrls []string
	if store.Banner != "" {
		utils.UnmarshalJSON(store.Banner, &bannerUrls)
		for i, url := range bannerUrls {
			if len(url) > 0 && url[0] == '/' {
				bannerUrls[i] = baseURL + strings.ReplaceAll(url, "\\", "/")
			}
		}
	}

	// 构建返回数据
	storeData := map[string]interface{}{
		"id":             store.Id,
		"name":           store.Name,
		"address":        store.Address,
		"type_id":        venueTypes,
		"latitude":       store.Latitude,
		"longitude":      store.Longitude,
		"logo":           store.Logo,
		"images":         imageUrl,
		"banner":         bannerUrls,
		"business_hours": store.BusinessHours,
		"contact_person": store.ContactPerson,
		"phone":          store.Phone,
		"description":    store.Description,
		"facilities":     store.Facilities,
		"notice":         store.Notice,
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取门店详情成功",
		"data":    storeData,
	}
	c.ServeJSON()
}

// 计算两点之间的距离（km）
func calculateDistance(lat1, lng1, lat2, lng2 float64) float64 {
	radLat1 := lat1 * math.Pi / 180.0
	radLat2 := lat2 * math.Pi / 180.0
	a := radLat1 - radLat2
	b := lng1*math.Pi/180.0 - lng2*math.Pi/180.0
	s := 2 * math.Asin(math.Sqrt(math.Pow(math.Sin(a/2), 2)+
		math.Cos(radLat1)*math.Cos(radLat2)*math.Pow(math.Sin(b/2), 2)))
	s = s * 6378.137 // 地球半径
	s = math.Round(s*10000) / 10000
	return s
}

// 格式化距离显示
func formatDistance(distance float64) string {
	if distance < 1 {
		return strconv.FormatInt(int64(distance*1000), 10) + "m"
	}
	return strconv.FormatFloat(distance, 'f', 2, 64) + "km"
}
